package com.vvv.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vvv.domain.LoginUser;
import com.vvv.domain.Result;
import com.vvv.domain.User;
import com.vvv.mapper.UserMapper;
import com.vvv.service.LoginService;
import com.vvv.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author vvv
 * @date 2023-06-11 15 04
 * discription
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 自定义登录接口
     * @return
     */
    @Override
    public Result login(User user) {
        // 1. 将user封装成Authentication对象
        Authentication authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 2. 调用AuthenticationManager的authenticate方法进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 2.1 为空，则认证失败
        if (authenticate == null) {
            throw new RuntimeException("登录失败");
        }
        // 3. 将userId，生成JWT
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJWT(userId);
        // 4. 将用户信息保持到redis中
        String key = "login:" + userId;
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(loginUser));
        // 5. 返回JWT
        return Result.ok(token);
    }
}

